<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Department;
use app\common\model\Equipment;
use \app\common\model\Hospital as HospitalModel;
use think\Db;
use think\Exception;
use think\Response;

/**
 * 医院接口
 */
class Hospital extends Api
{
    protected $noNeedLogin = ['all','search','getengineer'];
    protected $noNeedRight = ['*'];

    /**
     * 所有医院
     *
     */
    public function all()
    {
        $list=HospitalModel::all();
        $this->success('成功',$list);
    }
    /**
     * 搜索医院
     * */
    public function search(){
        //if(!$this->request->post('name') || empty($this->request->post('name')))  $this->error('提交失败：请输入搜索关键字' );
        $name = $this->request->post('name')? $this->request->post('name'):'';
        $list=HospitalModel::whereLike("name","%".$name."%")->select();
        $this->success('成功',$list);
    }

    /**
     * 首页统计
     * */
    public function getNum(){
        $user=$this->auth->getUser();
        $hospital=HospitalModel::where('FIND_IN_SET("'.$user["id"].'", user_ids)')->find();
        if(empty($hospital))  $this->error('该用户未绑定医院');
        $list=[];
        $list["repair"]=\app\common\model\work\Warranty::where(["hospital_id"=>$hospital["id"]])->where(" status != '3'")->count();//已报修
        $list["done"]=\app\common\model\work\Warranty::where(["hospital_id"=>$hospital["id"],"status"=>3])->count();//已完成
        $list["hand"]=\app\common\model\work\Warranty::where(["hospital_id"=>$hospital["id"],"status"=>1])->count();//进行中
        $this->success('成功',$list);
    }
    /**
     * 添加医院
     * */
    public function add(){
        $user = $this->auth->getUser();
        $data=[
            ['name', 'require', '医院名称不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/', '电话不能为空|手机号码格式错误'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $list=\app\common\model\Hospital::where(["name"=>$param["name"]])->find();
        if($list) $this->error("该医院已存在");
        $param["createtime"]=time();
        $param["founder_id"]=$user["id"];
        \app\common\model\Hospital::create($param);
        $this->success('成功');
    }
    /**
     * 添加科室
     * */
    public function addDepar(){
        $user = $this->auth->getUser();
        //$user["id"]=1;
        $data=[
            ['name', 'require', '科室名称不能为空'],
            ['hospital_id', 'require', '医院id不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $Hospital=\app\common\model\Hospital::where(["id"=>$param["hospital_id"],"status"=>'1'])->find();
        if(empty($Hospital))$this->error('该医院不存在');
        $list=Department::where(["name"=>$param["name"],"hospital_id"=>$param["hospital_id"]])->find();
        if($list) $this->error("该科室已存在");
        $param["createtime"]=time();
        $param["founder_id"]=$user["id"];
        Department::create($param);
        $this->success('成功');
    }
    /**
     * 添加设备
     * */
    public function addEquip(){
        $user = $this->auth->getUser();
        $data=[
            ['name', 'require', '设备名称不能为空'],
            ['marking', 'require', '型号不能为空'],
            ['serial', 'require', '序列号不能为空'],
            ['department_id', 'require', '科室id不能为空'],
            ['hospital_id', 'require', '医院id不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $Hospital=\app\common\model\Hospital::where(["id"=>$param["hospital_id"],"status"=>'1'])->find();
        if(empty($Hospital))$this->error('该医院不存在');;
        $Department=Department::where(["id"=>$param["department_id"],"status"=>'1'])->find();
        if(empty($Department))$this->error('该科室不存在');
        $param["createtime"]=time();
        $param["next_json"]=json_encode([]);
        $param["founder_id"]=$user["id"];
        Db::startTrans();
        try {
            $model=new Equipment();
            $result=$model->allowField(true)->insertGetId($param);
            $text = "http://ylsbr.westts.cn/?id=".$result;
            $qrInfo = $this->buildQrcode($text,$result);//$userInfo['nickname']);
            $model->where(["id"=>$result])->update(["image"=>$qrInfo]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    // 生成二维码
    public function buildQrcode($text,$label)
    {
        $params = [
            'text'           => $text,
            'label'           => $label,
            'size'           => 350,    //大小
            'padding'        => 15,    //内边距
            'errorlevel'     => 'medium',   //容错级别:low-低   medium-中等   quartile-高   high-超高
            'foreground'     => "#000000",     //前景色
            'background'     => "#ffffff",  //背景色
            'logo'           => 0,    //Logo:1-显示，0-不显示
            'logosize'       => '',  //Logo大小
            'labelfontsize'  => 14, //标签大小
            'labelalignment' => 'center',    //标签水平位置:left-左  center-中   right-右
        ];

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $response = Response::create()->header("Content-Type", "image/png");

        // 直接显示二维码
        /* header('Content-Type: ' . $qrCode->getContentType());
         $response->content($qrCode->writeString());*/

        // 写入到文件
        $fileUrl = '/uploads/qrcode/equipment/' . $label . '.png';
        $filePath = ROOT_PATH .'public'. $fileUrl;
        if (!file_exists(ROOT_PATH .'public/uploads/qrcode/')) mkdir (ROOT_PATH .'public/uploads/qrcode/',0777,true);
        if (!file_exists(ROOT_PATH .'public/uploads/qrcode/equipment/')) mkdir (ROOT_PATH .'public/uploads/qrcode/equipment/',0777,true);

        $qrCode->writeFile($filePath);

        $filePath=cdnurl(".".$fileUrl);
        return $filePath;
    }

    /**
     * 获取工程师
     * */
    public function getengineer(){
        $list=\app\common\model\User::field("id,nickname,avatar")->where(["identity"=>'1',"status"=>'1'])
            ->whereLike("nickname","%".$this->request->param("nickname")."%")
            ->select();
        $this->success('成功',$list);
    }
}
